/* (C)2024 */
package com.example.gradu.graduationproject.util;

import java.util.Collections;

import com.coze.openapi.client.chat.CreateChatReq;
import com.coze.openapi.client.chat.model.ChatEvent;
import com.coze.openapi.client.chat.model.ChatEventType;
import com.coze.openapi.client.connversations.message.model.Message;
import com.coze.openapi.service.auth.TokenAuth;
import com.coze.openapi.service.config.Consts;
import com.coze.openapi.service.service.CozeAPI;
import org.springframework.stereotype.Component;
import io.reactivex.Flowable;

/*
 * This example is about how to use the streaming interface to start a chat request
 * and handle chat events
 * */


@Component // 新增注解
public class StreamChat {
    String botIDTextToImage = "7476069152592052224";  // 文生图
    String botIDTextPolishing = "7476102634110844928";  // 文章润色
    String botIDCorrectMisspellings = "7476105808577822754";  // 错别字纠正
    String botIDFullTextSummary = "7476110717956243466";  // 全文总结

    public R TextToImage(String text){
        return chatStream(botIDTextToImage,text);
    }

    public R TextPolishing(String text){
        return chatStream(botIDTextPolishing,text);
    }

    public R CorrectMisspellings(String text){
        return chatStream(botIDCorrectMisspellings,text);
    }

    public R FullTextSummary(String text){
        return chatStream(botIDFullTextSummary,text);
    }

    public  R chatStream(String botID,String text) {
        String token = "pat_MvciPXqyoGNWos43EIneHAkgLnXaECXwnnKfWVchYhNca5p0NNeS1JcpBS9nUcUX";
        String userID = "testuser";
        TokenAuth authCli = new TokenAuth(token);


        CozeAPI coze =
                new CozeAPI.Builder()
                        .baseURL(Consts.COZE_CN_BASE_URL)
                        .auth(authCli)
                        .readTimeout(10000)
                        .build();
        CreateChatReq req =
                CreateChatReq.builder()
                        .botID(botID)
                        .userID(userID)
                        .messages(Collections.singletonList(Message.buildUserQuestionText(text)))
                        .build();

        Flowable<ChatEvent> resp = coze.chat().stream(req);
//        处理流式事件
        StringBuilder result = new StringBuilder();
        resp.blockingForEach(
                event -> {
                    if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) {
                        System.out.print(event.getMessage().getContent());
                        result.append(event.getMessage().getContent());
                    }
                });
        System.out.println("done");
        String imageUrl = result.toString();
        coze.shutdownExecutor();
        return R.ok().setData(imageUrl);
    }


}
